const Jwt = require('jsonwebtoken');
const Variable = require('../utils/variable');
const {
    secret
} = Variable;

const checkToken = async (ctx, next) => {
    // 从请求头里获取token
    let token = ctx.headers['Authorization'];

    if (!token) {
        ctx.body = {
            code: 401,
            msg: 'token不能为空！'
        };
    } else {
        Jwt.verify(token, secret, async err => {
            if (err) {
                if (err.name == 'TokenExpiredError') {
                    ctx.body = {
                        code: 401,
                        msg: 'token已过期！'
                    };
                } else {
                    ctx.body = {
                        code: 401,
                        msg: 'token已失效！'
                    };
                }
            }
        });
    }

    await next();
};

module.exports = checkToken;